package com.example.lenovo_.healthyangel;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lenovo_.healthyangel_menus.Personal_InforActivity;
import com.example.lenovo_.healthyangel_menus.Personal_Infor_EditorActivity;
import com.example.lenovo_.myactivity.LoginActivity;
import com.example.lenovo_.myfragment.HomeFragment;
import com.example.lenovo_.myfragment.ShopFragment;
import com.example.lenovo_.myfragment.SportFragment;
import com.example.lenovo_.myfragment.ValueFragment;
import com.example.lenovo_.myutils.AndUtils;
import com.example.lenovo_.myutils.SendRequest;
import com.example.lenovo_.myutils.SendUtils;
import com.example.lenovo_.myutils.SharedPfUtils;
import com.example.lenovo_.myutils.UrlUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements OnClickListener,NavigationView.OnNavigationItemSelectedListener {

	private Ihander handler = new Ihander();
	private SharedPfUtils mSharedPfUtils;
	private SendUtils sendinfor = new SendUtils();
	private TextView name;

	// tab 有关的控件
	private LinearLayout[] tab = new LinearLayout[4];
	private ImageButton[] tab_Imgbtn = new ImageButton[4];
	private TextView[] tab_Text = new TextView[4];
	private Fragment[] tab_Fragment = new Fragment[4];

	// tab 有关的控件ID
	private int[] tab_Id = { R.id.tab01, R.id.tab02, R.id.tab03, R.id.tab04 };
	private int[] tabImgbtn_Id = { R.id.tab_Imgbtn_01, R.id.tab_Imgbtn_02, R.id.tab_Imgbtn_03, R.id.tab_Imgbtn_04
			 };
	private int[] tabText_Id = { R.id.tab_Txt_01, R.id.tab_Txt_02, R.id.tab_Txt_03, R.id.tab_Txt_04 };

	// tab不同状态时图标的资源
	private int[] imgBtnNormal = { R.mipmap.home0, R.mipmap.shop0, R.mipmap.sport0, R.mipmap.privatefixedvalue0 };
	private int[] imgBtnChosen = { R.mipmap.home, R.mipmap.shop, R.mipmap.sport, R.mipmap.privatefixedvalue };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

		initView();

		setSelect(0);

		Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
		toolbar.setTitle("首页");
		//setSupportActionBar(toolbar);
		DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
				this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
		drawer.setDrawerListener(toggle);
		toggle.syncState();

		NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
		navigationView.setNavigationItemSelectedListener(this);

		// 测试网络
		if (AndUtils.isNetworkAvailable(MainActivity.this)) {
			// 判断用户名和密码是否正确
			JSONObject json = new JSONObject();
			try {
				json.put("id", mSharedPfUtils.getId());
				json.put("nick_name", mSharedPfUtils.getName());
				json.put("password", mSharedPfUtils.getPassword());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			sendinfor.setSendRequest(json);
			sendinfor.setRequestPath(UrlUtils.UrlUserCheck);
			SendRequest send = new SendRequest(sendinfor, handler);
			send.StartRequest();

		} else {
			Toast.makeText(this, "网络不可用", Toast.LENGTH_LONG).show();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/*点击返回键，退出App*/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode==KeyEvent.KEYCODE_BACK){
			moveTaskToBack(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();

		//noinspection SimplifiableIfStatement
		if (id == R.id.action_settings) {
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings("StatementWithEmptyBody")
	@Override
	public boolean onNavigationItemSelected(MenuItem item) {
		// Handle navigation view item clicks here.
		int id = item.getItemId();

		if (id == R.id.personal_Infor) {
			Intent intent=new Intent();
			intent.setClass(MainActivity.this,Personal_InforActivity.class);
			startActivity(intent);
			// 跳转到个人信息界面
		} else if (id == R.id.my_collection) {

		} else if (id == R.id.my_wallet) {

		} else if (id == R.id.health_plan) {

		} else if (id == R.id.settings) {

		} else if (id == R.id.quit) {
			//onBackPressed();
			showDialogquit();
		}

		DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		drawer.closeDrawer(GravityCompat.START);
		return true;


	}

	private void showDialogquit(){
		android.support.v7.app.AlertDialog.Builder builder=new android.support.v7.app.AlertDialog.Builder(this);
		builder.setTitle("退出登录");//设置标题
		builder.setIcon(R.mipmap.icon);//设置图标
		builder.setMessage("是否退出登录？");//设置内容
		builder.setPositiveButton("确认退出", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(MainActivity.this,"退出成功",Toast.LENGTH_SHORT);
				// 清除本地存储标志位，以防跳入登录界面后再跳回来
				mSharedPfUtils.setIsKeepUser(false);
				// 跳转到登录界面
                Intent intent=new Intent();
                intent.setClass(MainActivity.this, LoginActivity.class);
                startActivity(intent);
				MainActivity.this.finish();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		android.support.v7.app.AlertDialog dialog =builder.create();//获取一个Dialog
		dialog.show();//显示对话框
	}
	public class Ihander extends Handler { // 新建子类handler用于处理线程发回的信息

		@Override
		public void handleMessage(Message msg) {

			int flag = msg.what;
			switch (flag) {
				case 1:
					Toast.makeText(MainActivity.this, "账号信息无变更", Toast.LENGTH_LONG).show();
					break;
				case 2:
					Toast.makeText(MainActivity.this, "账号信息有变更请重新登录", Toast.LENGTH_LONG).show();
					// 清除本地存储标志位，以防跳入登录界面后再跳回来
					mSharedPfUtils.setIsKeepUser(false);
					// 跳转到登录界面
					Intent in = new Intent(MainActivity.this, LoginActivity.class);
					startActivity(in);
					break;
				case 3:

					break;
				case 4:

					break;
				default:
					break;
			}
		}
	}

	@Override
	public void onBackPressed() {
		// 点击返回按钮时给出提醒 询问是否退出

		new AlertDialog.Builder(MainActivity.this).setTitle("系统提示").setMessage("您确定要退出淘爱心吗？")
				.setPositiveButton("取消", null).setNegativeButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		}).show();

	}

	private void initView() {

		mSharedPfUtils = new SharedPfUtils(this, SharedPfUtils.SPFILEUSERINFO);

		for (int i = 0; i < 4; i++) {
			tab[i] = (LinearLayout) findViewById(tab_Id[i]);
			tab_Imgbtn[i] = (ImageButton) findViewById(tabImgbtn_Id[i]);
			tab_Text[i] = (TextView) findViewById(tabText_Id[i]);

		}

		initEvent();

	}

	private void initEvent() {

		for (int i = 0; i < 4; i++) {
			tab[i].setOnClickListener(this); // tab点击事件
		}

	}

	@Override
	public void onClick(View v){
        resetTab();
        switch (v.getId()){
            case R.id.tab01:
                setSelect(0);
                Toolbar toolbar0 = (Toolbar) findViewById(R.id.toolbar);//修改标题
                toolbar0.setTitle("首页");
                break;
            case R.id.tab02:
                setSelect(1);
                Toolbar toolbar1 = (Toolbar) findViewById(R.id.toolbar);
                toolbar1.setTitle("店铺");
                break;
            case R.id.tab03:
                setSelect(2);
                Toolbar toolbar2 = (Toolbar) findViewById(R.id.toolbar);
                toolbar2.setTitle("运动");
                break;
            case R.id.tab04:
                setSelect(3);
                Toolbar toolbar3 = (Toolbar) findViewById(R.id.toolbar);
                toolbar3.setTitle("私人订制");
                break;
            default:
                break;
        }
    }

	/*
	 * 初始化底部tab
	 */
	private void resetTab() {
		for (int i = 0; i < 4; i++) {
			tab_Imgbtn[i].setImageResource(imgBtnNormal[i]);
			tab_Text[i].setTextColor(0xff666666);
		}
	}

	/*
	 * 切换事件
	 */

	private void setSelect(int i) {

		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();

		hideTabFragment(transaction);

		switch (i) {
			case 0:

				if (tab_Fragment[0] == null) {
					tab_Fragment[0] = new HomeFragment();
					transaction.add(R.id.id_content, tab_Fragment[0]);
				} else {
					transaction.show(tab_Fragment[0]);
				}

				tab_Imgbtn[0].setImageResource(imgBtnChosen[0]);
				tab_Text[0].setTextColor(0xff070DBA);
				break;

			case 1:

				if (tab_Fragment[1] == null) {
					tab_Fragment[1] = new ShopFragment();
					transaction.add(R.id.id_content, tab_Fragment[1]);
				} else {
					transaction.show(tab_Fragment[1]);
				}

				tab_Imgbtn[1].setImageResource(imgBtnChosen[1]);
				tab_Text[1].setTextColor(0xff070DBA);
				break;

			case 2:

				if (tab_Fragment[2] == null) {
					tab_Fragment[2] = new SportFragment();
					transaction.add(R.id.id_content, tab_Fragment[2]);
				} else {
					transaction.show(tab_Fragment[2]);
				}

				tab_Imgbtn[2].setImageResource(imgBtnChosen[2]);
				tab_Text[2].setTextColor(0xff070DBA);
				break;

			case 3:

				if (tab_Fragment[3] == null) {
					tab_Fragment[3] = new ValueFragment();
					transaction.add(R.id.id_content, tab_Fragment[3]);
				} else {
					transaction.show(tab_Fragment[3]);
				}

				tab_Imgbtn[3].setImageResource(imgBtnChosen[3]);
				tab_Text[3].setTextColor(0xff070DBA);
				break;

			default:
				break;
		}
		transaction.commit();
	}

	/*
	 * 隐藏fragment
	 */
	private void hideTabFragment(FragmentTransaction transaction) {

		for (int i = 0; i < 4; i++) {
			if (tab_Fragment[i] != null) {
				transaction.hide(tab_Fragment[i]);
			}
		}

	}

}
